﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FilStartUps_Mobile.Models;
using FilStartUps_Mobile.Helpers;
using FilStartUps_Mobile.FILAPI;
using System.Drawing;
using System.IO;
namespace FilStartUps_Mobile.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        FilStartUpsEntities db_connect = new FilStartUpsEntities();
        Session_Helper session_helper = new Session_Helper();

        public ActionResult Index()
        {
            try
            {
                var page = FilStartUpsAPI.GetPageNav();
                return View(page);
            }
            catch
            {

            }
            return View();
        }
        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegistrationModel register, FormCollection form)
        {
            byte[] imgpost;
            if (ModelState.IsValid)
            {
                Profile profile = new Profile();
                Member member = new Member();
                string code = Helpers.Helper.Create();
                string password = Helpers.Helper.HashPassword(register.password);
                member.emailaddress = register.emailaddress;
                member.confirmemailaddress = register.confirmemailaddress;
                member.datejoined = DateTime.Now;
                member.password = password;
                member.confirmpassword = password;
                member.member_flag = false;
                member.roleidFK = 2;
                member.secretanswer = form["txtsecretanswer"].Trim();
                member.validationcode = code;
                member.secretquestion = form["secretquestion"].Trim();
                db_connect.Members.Add(member);
                db_connect.SaveChanges();

                Image file = Image.FromFile("D:/Filstartups/Project/FilStartUps_Mobile/FilStartUps_Mobile/Content/images/banner-5.png");
                string filbase64 = ImageToBase64(file, System.Drawing.Imaging.ImageFormat.Png);
                imgpost = Convert.FromBase64String(filbase64);

                profile.image = imgpost;
                profile.memberidFK = member.memberidPK;
                profile.firstname = register.firstname;
                profile.lastname = register.lastname;
                db_connect.Profiles.Add(profile);
                db_connect.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(register);
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LogOnModel login)
        {
            string password = login.password == "" || login.password == null
           ? Helper.HashPassword("hahah") : Helper.HashPassword(login.password.Trim());

            var validate = db_connect.Members.Where(m => m.emailaddress.Equals(login.emailaddress)
                                    && m.password.Equals(password)).SingleOrDefault();

            if (validate != null)
            {
                //Create COOKIES
                bool checksession = session_helper.CheckSession(validate.memberidPK);
                if (checksession == true)
                {
                    session_helper.UpdateSession(validate.memberidPK);
                }
                else
                {
                    session_helper.CreateSession(validate.memberidPK);
                }
                return RedirectToAction("Index");
                // return Json(true, JsonRequestBehavior.AllowGet);
            }
            else
            {
                TempData["validation"] = "Invalid Username or Password";
                // return Json(false, JsonRequestBehavior.AllowGet);
            }
            return View();
        }

        public JsonResult ValidateUser(LogOnModel login)
        {
            string password = login.password == "" || login.password == null
                       ? Helper.HashPassword("hahah") : Helper.HashPassword(login.password.Trim());

            var validate = db_connect.Members.Where(m => m.emailaddress.Equals(login.emailaddress)
                                    && m.password.Equals(password)).SingleOrDefault();

            if (validate != null)
            {
                //Create COOKIES
                bool checksession = session_helper.CheckSession(validate.memberidPK);
                if (checksession == true)
                {
                    session_helper.UpdateSession(validate.memberidPK);
                }
                else
                {
                    session_helper.CreateSession(validate.memberidPK);
                }
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }

        }
        public ActionResult Activation()
        {
            string activationcode = Request.QueryString[""].Trim();
            string email = Request.QueryString["email"].Trim();


            return View();
        }

        public ActionResult Content()
        {
            //parse query string
            int pageid = int.Parse(Request.QueryString["p"]);
            //create a new instance
            var pagecategory = new PageCategory();
            //parse json to API
            var page = FilStartUpsAPI.GetPageInfo(pageid);
            var category = FilStartUpsAPI.GetPageSub(pageid);
            //pass value
            pagecategory.category = category;
            pagecategory.pagedescription = page;

            return View(pagecategory);
        }

        public ActionResult Articles()
        {
            //parse query string
            int catid = int.Parse(Request.QueryString["c"]);
            // create a new instance of class
            var category_post = new Category_Post();
            //parse json value
            var categorypost = FilStartUpsAPI.GetCategoryPost(catid);
            //pagesub parse
            var pagesub = FilStartUpsAPI.GetPageSub(categorypost.pageidFK);
            //pass value
            category_post.catpost = categorypost;
            category_post.category = pagesub;

            return View(category_post);
        }
        public ActionResult GetPostImage(string postid)
        {
            int postid_ = int.Parse(postid);
            var postimage = FilStartUpsAPI.GetPostImage(postid_);
            if (postimage != null)
            {
                //Convert base64string to byte
                byte[] image = Convert.FromBase64String(postimage.base64string);
                return File(image, postimage.imagetype);
            }
            else
            {
                Image fileimage = Image.FromFile("D:/Filstartups/Project/FilStartUps_Mobile/FilStartUps_Mobile/Content/images/banner-5.png");
                string base64string = ImageToBase64(fileimage, System.Drawing.Imaging.ImageFormat.Png);
                byte[] imgpost = Convert.FromBase64String(base64string);
                return File(imgpost, "jpeg");
                //return null;
            }
        }
        //Convert To Image
        public Image Base64ToImage(string base64String)
        {
            // Convert Base64 String to byte[]
            byte[] imageBytes = Convert.FromBase64String(base64String);
            MemoryStream ms = new MemoryStream(imageBytes, 0,
              imageBytes.Length);

            // Convert byte[] to Image
            ms.Write(imageBytes, 0, imageBytes.Length);
            Image image = Image.FromStream(ms, true);
            return image;
        }

        //Convert To Base64string
        public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                //convert image to byte[]
                image.Save(ms, format);
                byte[] imageBytes = ms.ToArray();

                //Convert byte[] to base64string
                string base64string = Convert.ToBase64String(imageBytes);
                return base64string;
            }
        }
        [HttpGet]
        public ActionResult LatestArticles()
        {
            var latest = FilStartUpsAPI.GetLatestArticles();
            if (latest.Count() > 0)
            {
                return View(latest);
            }
            else
            {
                return View();
            }
        }

        [HttpGet]
        public ActionResult FeaturedArticles()
        {
            var featured = FilStartUpsAPI.GetFeaturedPost();
            if (featured.Count() > 0)
            {
                return View(featured);
            }
            else
            {
                return View();
            }
        }


    }


}
